//
// Created by yeongguo(郭青云) on 2019-12-11.
//

#include <cstring>
#include "mp3_encode.h"
#include <android/log.h>
#include <jni.h>

#define TAG "mp3_encode"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定义LOGI类型

Mp3Encoder *encoder = NULL;
extern "C" {
JNIEXPORT jint JNICALL Java_com_chivan_encoder_Mp3Encoder_init
        (JNIEnv *env,
         jobject jobj,
         jint audioChannelsParam,
         jint bitRateParam,
         jint sampleRateParam,
         jint quality) {
    encoder = new Mp3Encoder();
    int ret = encoder->lint(sampleRateParam,
                            audioChannelsParam,
                            bitRateParam,
                            quality);
    return ret;
}


JNIEXPORT jbyteArray JNICALL Java_com_chivan_encoder_Mp3Encoder_encode
        (JNIEnv *env, jobject,
         jbyteArray buffer,
         jlong size) {
    jbyte *bytes = env->GetByteArrayElements(buffer, 0);
    EncodeData *encodeData = encoder->encode((short *) bytes, (long) size / 2);
    env->ReleaseByteArrayElements(buffer, bytes, 0);
    jbyteArray array = env->NewByteArray(encodeData->length);
    env->SetByteArrayRegion(array, 0, encodeData->length,
                            reinterpret_cast<jbyte *>(encodeData->data));
    delete encodeData;
    return array;
}


JNIEXPORT jint JNICALL Java_com_chivan_encoder_Mp3Encoder_destroy
        (JNIEnv *, jobject) {
    int result = 1;
    if (encoder != nullptr) {
        result = encoder->Destroy();
        delete encoder;
        encoder = nullptr;
    }
    return result;
}
}